package com.bing.spring;

import com.bing.bean.Component;
import com.bing.bean.Duter;
import com.bing.bean.Son;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by kaibb on 15-9-17.
 * 自定义ClassPathXmlApplicationContext.
 * 1. 测试postProcessBeanFactory
 * 2. 测试BeanPostProcessor
 *
 */
public class BingContext extends ClassPathXmlApplicationContext {

    private Map<String, String> values;

    private List<String> list;

    public BingContext() {
        values = new HashMap<>();
        list=new ArrayList<>();
        list.add("kaibing");
        list.add("hailii");
        refresh();
    }


    class InitContext implements BeanPostProcessor {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (values.containsKey(beanName)) {
                ((Component) bean).init(values.get(beanName));
            }
            return bean;
        }
    }

    @Override
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        super.postProcessBeanFactory(beanFactory);
        beanFactory.addBeanPostProcessor(new InitContext());

        BeanDefinitionRegistry registry = ((BeanDefinitionRegistry) beanFactory);
        GenericBeanDefinition son = new GenericBeanDefinition();
        son.setBeanClass(Son.class);
        son.setLazyInit(true);
        registry.registerBeanDefinition("son", son);
        values.put("son", "kaibing");

        GenericBeanDefinition duter = new GenericBeanDefinition();
        duter.setBeanClass(Duter.class);
        duter.setLazyInit(true);
        registry.registerBeanDefinition("duter", duter);
        values.put("duter", "haili");

        Map<String,List<String>> ma=new HashMap<>();
        ma.put("ma",list);
        GenericBeanDefinition map = new GenericBeanDefinition();
        map.setLazyInit(true);
        map.setBeanClass(HashMap.class);
        ConstructorArgumentValues cons =new ConstructorArgumentValues();
        cons.addIndexedArgumentValue(0,ma);
        map.setConstructorArgumentValues(cons);
        registry.registerBeanDefinition("map", map);

    }

}
